// 使用Pinia实现的用户状态管理模块
import { defineStore } from 'pinia'
import axios from 'axios'

// 用户信息类型定义
export interface User {
  id: string
  username: string
  role: 'user' | 'admin'
  [key: string]: any
}

// 登录参数类型
export interface LoginParams {
  username: string
  password: string
  remember?: boolean
}

// 登录响应类型
interface LoginResponse {
  success: boolean
  data?: {
    accessToken: string    // 访问令牌
    refreshToken: string   // 刷新令牌
    user: User
  }
  message?: string
}

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null as User | null,
    accessToken: localStorage.getItem('accessToken') || '',
    refreshToken: localStorage.getItem('refreshToken') || '',
    rememberPassword: localStorage.getItem('rememberPassword') === 'true' || false,
    savedUsername: localStorage.getItem('savedUsername') || ''
  }),

  getters: {
    isLoggedIn: (state) => !!state.accessToken,
    isAdmin: (state) => state.user?.role === 'admin'
  },

  actions: {
    // 登录
    async login(params: LoginParams) {
      try {
        // 实际项目中替换为真实API
        const response: LoginResponse = await axios.post('/login', params)

        if (response.success && response.data) {
          this.accessToken = response.data.accessToken
          this.refreshToken = response.data.refreshToken
          this.user = response.data.user

          // 保存到localStorage
          localStorage.setItem('accessToken', this.accessToken)
          localStorage.setItem('refreshToken', this.refreshToken)

          // 处理记住密码
          if (params.remember) {
            localStorage.setItem('rememberPassword', 'true')
            localStorage.setItem('savedUsername', params.username)
          } else {
            localStorage.removeItem('rememberPassword')
            localStorage.removeItem('savedUsername')
          }

          return { success: true }
        } else {
          return { success: false, message: response.message || '登录失败' }
        }
      } catch (error) {
        console.error('登录失败', error)
        return { success: false, message: '登录过程中发生错误' }
      }
    },

    // 刷新访问令牌
    async refreshAccessToken() {
      if (!this.refreshToken) {
        this.logout()
        return false
      }

      try {
        const response = await axios.post('/refresh', {
          refreshToken: this.refreshToken
        })

        if (response.data.success && response.data.data) {
          this.accessToken = response.data.data.accessToken
          localStorage.setItem('accessToken', this.accessToken)
          return true
        } else {
          this.logout()
          return false
        }
      } catch (error) {
        console.error('刷新令牌失败', error)
        this.logout()
        return false
      }
    },

    // 登出
    logout() {
      this.accessToken = ''
      this.refreshToken = ''
      this.user = null
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
    },

    // 获取当前用户信息
    async fetchCurrentUser() {
      if (!this.accessToken) return

      try {
        // 实际项目中替换为真实API
        const response = await axios.get('/user/info', {
          headers: { Authorization: `Bearer ${this.accessToken}` }
        })
        
        if (response.data.success) {
          this.user = response.data.data
        }
      } catch (error) {
        console.error('获取用户信息失败', error)
        this.logout() // 信息获取失败时登出
      }
    }
  }
})
